/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.Ventas;

import javax.swing.JDialog;
import javax.swing.table.AbstractTableModel;
import java.util.Date;
import Controlador.Service.Ventas.GestionVentas;
import Controlador.Bean.Ventas.LineaPlan;
import Controlador.Bean.Ventas.PlanVentas;
import Controlador.Service.Configuracion.GestionConfiguracion;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.JOptionPane;
import javax.swing.table.TableRowSorter;


/**
 *
 * @author Luis Enrique
 */
public class PlanVentasRegistrarPanel extends javax.swing.JPanel {
    private String flag;
    PedidoTableModel myTableModel;
    private JDialog parent;
    private PlanVentasMainPanel refSalesPanel;
    ArrayList<LineaPlan> lineas = new ArrayList<>();
    String codPlanVentas = GestionVentas.getInstance().getCodPlanVentas();
    int numPlanVentas = GestionVentas.getInstance().getCorrelativoPlanVentas();
    long maximo = GestionConfiguracion.getInstance().getCantMaxPlanVentas();
    Date ultimaFecha = GestionVentas.getInstance().getFechaPlanVentas();
    Date fechaReg = new Date ();
    Date fechaInicial;
    Date fechaFinal;
    
    public void setParent(JDialog parent){
        this.parent = parent;
    }
    
    public void setParentPanel(PlanVentasMainPanel panel){
        this.refSalesPanel = panel;
    }   
        
    class PedidoTableModel extends AbstractTableModel{
        String [] titles = {"Producto","Cantidad en Pedidos","Cantidad de Ajuste","Cantidad Final"};

        @Override
        public int getRowCount() {
            return lineas.size();
        }

        @Override
        public int getColumnCount() {
            return titles.length;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            String res=null;
            LineaPlan lp = lineas.get(rowIndex);
            switch(columnIndex){
                case 0: res = lp.getNombreProducto(); break;
                case 1: res = lp.getCantidad()+"";break;
                case 2: res = lp.getCantidadAjuste()+""; break;
                case 3: res = lp.getCantidadFinal()+"";break;
            }
            return res;
        }
        
        @Override
        public boolean isCellEditable(int row, int col) {
            if (col == 2){
                return true;
            } else {
                return false;
            }
        }
        
        @Override
        public void setValueAt(Object value,  int row, int col){
            LineaPlan lplan = lineas.get(row);
            long cantAjuste = Long.parseLong(value.toString());
            lplan.setCantidadAjuste(cantAjuste);
            lplan.setCantidadFinal(lplan.getCantidad()+cantAjuste);            
            refreshItemsTable2();
        }
        
        @Override
        public String getColumnName(int col){
            return titles[col];
        }
    }
    
    public PlanVentasRegistrarPanel() {
        initComponents();
        txtNumPlanVentas.setText(numPlanVentas+"");
        txtNumPlanVentas.setEnabled(false);
        dpFechaRegistro.setDate(fechaReg);
        dpFechaRegistro.setEnabled(false);
        dpFechaFin.setEnabled(false);
        
        //SETEA FECHA INICIAL
        Calendar c = Calendar.getInstance();
        c.setTime(this.ultimaFecha);
        c.add(Calendar.DATE,1);
        this.fechaInicial = c.getTime();
        dpFechaInicio.setDate(fechaInicial);
        dpFechaInicio.setEnabled(false);
        
        //SETEA FECHA FINAL
        c = Calendar.getInstance();
        c.setTime(this.fechaInicial);
        c.add(Calendar.DATE,GestionConfiguracion.getInstance().getDiasPlanVentas());
        this.fechaFinal = c.getTime();
        dpFechaFin.setDate(fechaFinal);
        dpFechaFin.setEnabled(false);
        
        myTableModel = new PedidoTableModel();
        tblProductos.setModel(myTableModel);
        TableRowSorter<PedidoTableModel> sorter = new TableRowSorter<PedidoTableModel> ((PedidoTableModel) tblProductos.getModel());
        tblProductos.setRowSorter(sorter);
    }

    public void refreshItemsTable(ArrayList<LineaPlan>lineasPlan){
        this.lineas = new ArrayList(lineasPlan);
        myTableModel.fireTableChanged(null);
        if(flag.equals("estimado")){
            tblProductos.getColumnModel().getColumn(1).setMaxWidth(0);
            tblProductos.getColumnModel().getColumn(1).setMinWidth(0);
            tblProductos.getColumnModel().getColumn(1).setPreferredWidth(0);
        }
    }
    
    public void refreshItemsTable2(){
        myTableModel.fireTableChanged(null);
        if(flag.equals("estimado")){
            tblProductos.getColumnModel().getColumn(1).setMaxWidth(0);
            tblProductos.getColumnModel().getColumn(1).setMinWidth(0);
            tblProductos.getColumnModel().getColumn(1).setPreferredWidth(0);
        }
    }
    
    public void estimado(){        
        this.flag = "estimado";
        ArrayList<LineaPlan> lineasConsulta = GestionVentas.getInstance().queryProdPlan2();
        refreshItemsTable(lineasConsulta);
    }
    
    public void pedidos(){
        this.flag = "pedidos";
        ArrayList<LineaPlan> lineasConsulta = GestionVentas.getInstance().queryProdPlan();
        refreshItemsTable(lineasConsulta);
    }
    
    public boolean valido(){
        boolean b = true;
        for(int i=0;i<lineas.size();i++){
            if(lineas.get(i).getCantidadAjuste()<0)
                b=false;
        }
        return b;
    }
    
    public boolean maximoValido(){
        for(int i=0;i<lineas.size();i++){
            if(lineas.get(i).getCantidadFinal()>maximo)
                return false;
        }
        return true;
    }
                
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblProductos = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jLabel10 = new javax.swing.JLabel();
        txtNumPlanVentas = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        dpFechaRegistro = new org.jdesktop.swingx.JXDatePicker();
        jLabel7 = new javax.swing.JLabel();
        dpFechaInicio = new org.jdesktop.swingx.JXDatePicker();
        jLabel8 = new javax.swing.JLabel();
        dpFechaFin = new org.jdesktop.swingx.JXDatePicker();
        jLabel9 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        taObservacion = new javax.swing.JTextArea();
        btnRegistrar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setMaximumSize(new java.awt.Dimension(784, 549));
        setMinimumSize(new java.awt.Dimension(784, 549));
        setPreferredSize(new java.awt.Dimension(784, 549));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Lista de Productos"));
        jPanel1.setToolTipText("");
        jPanel1.setMaximumSize(new java.awt.Dimension(764, 305));
        jPanel1.setMinimumSize(new java.awt.Dimension(0, 0));
        jPanel1.setPreferredSize(new java.awt.Dimension(764, 305));
        jPanel1.setLayout(new java.awt.BorderLayout());

        tblProductos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblProductos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(tblProductos);

        jPanel1.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Información del Plan de Ventas"));

        jLabel10.setText("Número de Plan de Ventas");

        jLabel3.setText("Fecha de Registro");

        jLabel7.setText("Fecha Inicio");

        jLabel8.setText("Fecha Fin");

        jLabel9.setText("Observaciones");

        taObservacion.setColumns(20);
        taObservacion.setRows(5);
        taObservacion.setMaximumSize(new java.awt.Dimension(164, 94));
        taObservacion.setMinimumSize(new java.awt.Dimension(164, 94));
        jScrollPane1.setViewportView(taObservacion);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel10)
                    .addComponent(jLabel3)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtNumPlanVentas, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(dpFechaRegistro, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(dpFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(55, 55, 55)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(jScrollPane1)))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(dpFechaFin, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNumPlanVentas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(dpFechaRegistro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(dpFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addComponent(jLabel8))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(dpFechaFin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(12, Short.MAX_VALUE))
        );

        btnRegistrar.setText("Registrar");
        btnRegistrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRegistrarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnRegistrar)
                        .addGap(18, 18, 18)
                        .addComponent(btnCancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnRegistrar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(72, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistrarActionPerformed
        if(!lineas.isEmpty()){
            if(valido()){
                if(maximoValido()){
                    PlanVentas plan = new PlanVentas(codPlanVentas,numPlanVentas,fechaReg,dpFechaInicio.getDate(),dpFechaFin.getDate(),taObservacion.getText(),"Registrado");
                    GestionVentas.getInstance().registrarPlanVentas(plan,lineas);
                    JOptionPane.showMessageDialog(this,"Se registró correctamente el plan de ventas.");
                    refSalesPanel.refreshItemsTable();
                    parent.dispose();
                }
                else
                    JOptionPane.showMessageDialog(this,"Las cantidades no deben exceder el máximo: "+maximo+".");      
            }
            else
                JOptionPane.showMessageDialog(this,"Las cantidades ingresadas deben ser mayores o iguales a 0.");      
        }
        else
            JOptionPane.showMessageDialog(this,"Debe seleccionar productos.");      
    }//GEN-LAST:event_btnRegistrarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        parent.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnRegistrar;
    private org.jdesktop.swingx.JXDatePicker dpFechaFin;
    private org.jdesktop.swingx.JXDatePicker dpFechaInicio;
    private org.jdesktop.swingx.JXDatePicker dpFechaRegistro;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea taObservacion;
    private javax.swing.JTable tblProductos;
    private javax.swing.JTextField txtNumPlanVentas;
    // End of variables declaration//GEN-END:variables
}
